#!/usr/bin/python3
# coding=utf-8
# 回放csv录制内容

import pyautogui as pg
import time
import win32gui, win32ui, win32con, win32api
import pandas as pd
import rec_csv
import numpy as np
import threading

from imp import reload
reload(rec_csv)
import screenshot
reload(rec_csv)


# def _cts(S, pts):
#     '''
#     S 客户窗口对于屏幕的坐标
#     pts 将一大堆相对坐标，原点在客户区左上角，转换成屏幕坐标
#     '''
#     deta = np.array([S[0] - (-8), S[1]])
#     return pts + deta
#     pass

thread_stop = False;
thread_pause = False;
def do_replay(
        data, 
        start, end, 
        fn_start,
        title = u"无标题 - 画图",
        _pause=0.01,
        _en_screenshot=False,
        _screenshot_delay=0.2):
    '''
    暂停回放 pause
    取消回放 esc
    screenshot 是否截图
    '''
    global thread_stop
    global thread_pause


    hwnd = win32gui.FindWindow(0, title)
    if not hwnd:
        print(data.iloc[start])
        print("找不到窗口 [%s]" %(title))
        return 1
    win32gui.ShowWindow(hwnd, True)
    win32gui.SetForegroundWindow(hwnd)  # 窗口调整到前台
    
    
    # data = pd.read_csv(fname)

    pg.PAUSE=_pause
    
    pts = np.array([data['rel-x'],data['rel-y']]).T
    rect = win32gui.GetWindowRect(hwnd)

    
    ss_ind = int(fn_start)
    
    for i in range(start, end):
        while thread_pause:
            time.sleep(1)
            
        if thread_stop:
            break
        # x, y = win32gui.ClientToScreen(hwnd, (pts[i][0], pts[i][1]))
        x, y = pts[i][0], pts[i][1]
        win32gui.SetForegroundWindow(hwnd)  # 窗口调整到前台
        if not win32gui.IsWindow(hwnd):
            print("unknow")
            return
        if data.loc[i]['mouse-action'] == 'click':
            pg.click(x, y, _pause=0.2)
            pass
        elif data.loc[i]['mouse-action'] == 'down':
            pg.mouseDown(x, y, _pause=0.2)
        elif data.loc[i]['mouse-action'] == 'doubleclick':
            print('ddddf')
            pg.doubleClick(x, y, _pause=1)
            time.sleep(1)
        elif data.loc[i]['mouse-action'] == 'move':
            # pg.moveTo(pts[i][0], pts[i][1])
            pg.moveTo(x, y)
        elif data.loc[i]['mouse-action'] == 'up':
            pg.mouseUp(x, y, _pause=0.2)
            if _en_screenshot:
                time.sleep(_screenshot_delay)
                screenshot.capture_window(title=title, fname="log/" + str(ss_ind) + ".bmp", in_hwnd=hwnd)
                ss_ind = ss_ind + 1
        else:
            print("un know ")
    return ss_ind

########################################################################
# 后台按键监控

from pynput import keyboard

def _on_release(key):
    '''
    在按下esc时候终结 “回放”
    '''
    global thread_stop
    global thread_pause
    
    if key == keyboard.Key.esc:
        thread_stop = True;
        return False
    if key == keyboard.Key.pause:
        thread_pause = not thread_pause;


def _thread_monitor_key_on_relay():
    with keyboard.Listener(
        on_release = _on_release) as listener:
        listener.join()

    pass
########################################################################

if __name__ == '__main__':
    t = threading.Thread(target=_thread_monitor_key_on_relay)
    t.start()
    
    data = pd.read_csv("unname.csv")
    data['wintitle'] = '桌面'
    groups = rec_csv.split_csv(data)
    # print(groups)
    # print(len(groups[1]))
    ig = 1
    fn_start = 0;
    
    
    for group in groups:
        # if np.isnan(data.iloc[group[0]]['wintitle']):
            # print("dd")
        fn_start = do_replay(data, 
                            group[0], 
                            group[1], 
                            fn_start, 
                            data.iloc[group[0]]['wintitle'], 
                            _pause=0.1,
                            _en_screenshot=True,
                            _screenshot_delay=0)
    